package com.forcedotcom
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileReference;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.utils.ByteArray;
	
	public class ImageLoader extends EventDispatcher
	{
		public function ImageLoader()
		{
		}
		
		private var stream:URLStream;
		private var conn:AccountConnection;
		private var imageBytes:ByteArray;
		private var saveReference:FileReference;
		
		public function loadImage(connection:AccountConnection):void
		{
			conn = connection;
			var url:String = "https://www.salesforce.com/login.jsp?un=" +
					conn.userName + "&pw=" + 
					conn.password + "&startUrlL=/userphoto?u=" + 
					conn.loginResult.userId + "&v=1&s=T";
			
			var loader:URLLoader = new URLLoader();
			configureListeners(loader);

			var req:URLRequest = new URLRequest(url);
			req.followRedirects = true;

			//stream = new URLStream();
			//req.addEventListener(Event.COMPLETE, onBytesLoaded);
			//req.addEventListener(IOErrorEvent.IO_ERROR, onBytesIOError);
			//req.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onBytesSecurityError);

			try
			{
				loader.load(req);
				//stream.load(new URLRequest(url));
			}
			catch(err2:Error)
			{
				trace(err2);
			}
		}
	
		private function onBytesIOError(event:IOErrorEvent):void {destroyStream();}
		private function onBytesSecurityError(event:SecurityErrorEvent):void {destroyStream();}

		private function configureListeners(dispatcher:IEventDispatcher):void {
			dispatcher.addEventListener(Event.COMPLETE, completeHandler);
			dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onBytesSecurityError);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, onBytesIOError);
		}

		private function completeHandler(event:Event):void {
			var loader:URLLoader = URLLoader(event.target);
			trace("completeHandler: " + loader.data);
			dispatchEvent(new Event("profilePicLoadComplete"));
		}

		private function destroyStream():void
		{
			if(stream)
			{
				try
				{
					stream.close();
				}
				catch(err:Error)
				{}
				stream.removeEventListener(Event.COMPLETE, onBytesLoaded);
				stream.removeEventListener(IOErrorEvent.IO_ERROR, onBytesIOError);
				stream.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onBytesSecurityError);
				stream = null;
			}
		}
		
		private function onBytesLoaded(event:Event):void
		{
			imageBytes = new ByteArray();
			stream.readBytes(imageBytes, 0, stream.bytesAvailable)
			conn.profileImageSource = imageBytes;
			destroyStream();
		}
	}
}